package com.token.iot.bratterycharging.gateway;



import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.outstanding.framework.base.TransactionLogger;
import com.token.iot.bratterycharging.gateway.server.BratteryChargingServerInitializer;
import com.token.iot.bratterycharging.gateway.server.BratteryChargingThread;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;


@Component
public class Start implements ApplicationListener<ApplicationContextEvent> {

	private Logger logger = LoggerFactory.getLogger(Start.class);

	private ChannelFuture future;

	private ServerBootstrap bootstrap;

	@Value("${iot.bratterycharging.port:9001}")
	private int port = 9001;

	@Autowired
	private BratteryChargingServerInitializer bratterychargingServerInitializer;

	private EventLoopGroup bossGroup = new NioEventLoopGroup();
	private EventLoopGroup workerGroup = new NioEventLoopGroup();

	@PostConstruct
	public void start() {
	}

	
	@PreDestroy
	public void destory() {
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
	}

	
	@Override
	public void onApplicationEvent(ApplicationContextEvent event) {
		if (event.getApplicationContext().getParent() != null)
			return;
		
		if (event instanceof ContextRefreshedEvent) {
			bootstrap = new ServerBootstrap();
			bootstrap.group(bossGroup, workerGroup);
			bootstrap.channel(NioServerSocketChannel.class);
			bootstrap.childHandler(bratterychargingServerInitializer);
			BratteryChargingThread t = new BratteryChargingThread(future, bootstrap, port);
			
			t.start();
			logger.debug("The application has been successfully started");
		} else if (event instanceof ContextClosedEvent) {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
			logger.debug("The application has been successfully stoped");
		}
	}
}


